<?php
namespace app\common\logic;

use think\Db;

class ArticleSort extends Base
{
    /*
     * 后期需要添加缓存的有getAllSubIds (后台修改文章所属类别，添加文章，修改等级列表均删除当前缓存)
     *
     *
     *
     *
     */


    // 获取平级树
    private function flatTree($data, $pid = 0, &$result = [])
    {
        foreach ($data as $item)
        {
            if ($item['pid'] == $pid) {
                $result[] = $item;
                $this->flatTree($data, $item['id'], $result);
            }
        }
        return $result;
    }

    // 获取等级树
    private function levelTree($data, $pid = 0)
    {
        $tree = [];
        foreach ($data as $key =>$item) {
            if ($item['pid'] == $pid) {
                unset($data[$key]);
                $item['son'] = $this->levelTree($data, $item['id']);
                if (empty($item['son'])) {
                    unset($item['son']);
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }

    // 当前等级包含的文章量
    private function levelNumTree($data, $pid = 0, &$result = [], &$num = 0)
    {
        foreach ($data as $item)
        {
            if ($item['pid'] == $pid) {
                $this->levelNumTree($data, $item['id'], $result, $num);
                $num += $item['num'];
                $item['num'] = $num;
                $result[] = $item;
            }
        }
        return $result;

//        $tree = [];
//        foreach ($data as $key =>$item) {
//            if ($item['pid'] == $pid) {
//                unset($data[$key]);
//                $item['son'] = $this->levelTree($data, $item['id']);
//                if (empty($item['son'])) {
//                    unset($item['son']);
//                } else {
//                    $item['num'] +=
//                }
//                $tree[] = $item;
//            }
//        }
//        return $tree;
    }



    // 获取所有子类的id (平级展示 -- 用于面包屑等环境)
    public function getAllSubIds($id, $is_oneself = false)
    {
        $data = Db::name('article_sort')->select();
        $oneself = Db::name('article_sort')->where('id',$id)->find();
        $list = $this->flatTree($data, $id);
        if ($is_oneself) {
            array_unshift($list, $oneself);
        }
        $rt = $list;
        return $rt;
    }

    // 获取当前类型下所有文章数量
    public function getCategoryAllNum()
    {
        // 获取某个id下所有子集
        // 获取他的文章量。
        // 累加
        $list = Db::name('article_sort')->select();
        $num_arr = $this->logic()->article()->category();
        $num_arr = array_column($num_arr, 'num', 'sort_id');
        foreach ($list as &$item) {
            $item['num'] = isset($num_arr[$item['id']])?$num_arr[$item['id']]:15;
        }
        $rt = $this->levelNumTree($list);
        return $rt;
    }
}